const request = require('request');
const extend = require('extend');
const fs = require('fs');

const weChatUtil = {
    token_url: 'https://api.weixin.qq.com/cgi-bin/token',
    message_url: 'https://api.weixin.qq.com/cgi-bin/message',
    menu_url: 'https://api.weixin.qq.com/cgi-bin/menu',
    group_url: 'https://api.weixin.qq.com/cgi-bin/groups',
    media_url: 'https://api.weixin.qq.com/cgi-bin/media/uploadimg',
    material_url: 'https://api.weixin.qq.com/cgi-bin/material',
    config: {
        appid: 'wxf3e1063abaf889ab',
        mch_id: '1316675801',
        // secret: '511e4629bb152201fe939e1665d132c7',
        secret: '9c71766b86c4d1a56caa90aa9dac8eb4',
        key: 'vc8fhbrmUaE9Z1EMuI48usyLeyNJ0201'
    }
};

/**
 * 获取token
 * @param callback
 */
weChatUtil.getToken = function (callback) {
    let _this = this;
    request({
        method: 'get',
        uri: _this.token_url + "?appid=" + _this.config.appid + "&secret=" + _this.config.secret + "&grant_type=client_credential"
    }, function (error, response, body) {
        if (error)
            throw error;
        console.log("weChatUtil.getToken:@" + body + "@");
        let retData = JSON.parse(body);
        if (retData.access_token) {
            callback(retData.access_token);
        } else {
            console.log("fetch token error!");
        }
    });
};

/**
 * 发送微信消息
 * @param message
 */
weChatUtil.templateMessage = function (message, callback) {
    let _this = this;
    _this.getToken(function (token) {
        //var message = {
        //    touser: "opkN1t-njzuumf7t2d3Xlw8sUg2U",//openid
        //    template_id: "UdFYzwb7GdGH25-kx69vkbz4wOBwHuWWjocmJF34HYM",//
        //    url: "www.baidu.com",
        //    topcolor: "#FF0000"
        //};
        //message.data = {
        //    title: {value: "aa", color: "#173177"},
        //    keyword1: {value: "aa", color: "#173177"},
        //    keyword2: {value: "aa", color: "#173177"},
        //    remark: {value: "aa", color: "#173177"}
        //}
        request({
            method: 'post',
            uri: _this.message_url + "/template/send?access_token=" + token,
            //form: message
            body: JSON.stringify(message),
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            }
        }, function (error, response, body) {
            if (error) {
                console.log(error);
            }
            console.log("weChatUtil.templateMessage:@" + body + "@");
            let retData = JSON.parse(body);
            if (retData.errcode === 40001) {
                _this.tokenCache.tokenTime = 0;
            }
            callback(body);
        });
    });
};

weChatUtil.previewMessage = function (data,callback) {
    let _this = this;
    _this.getToken(function (token) {
        request({
            method: 'post',
            uri: _this.message_url + "/mass/preview?access_token=" + token,
            json: data
        }, function (error, response, body) {
            if (error)
                throw error;
            callback(body);
        });
    });
};

weChatUtil.massMessage = function (data,callback) {
    let _this = this;
    _this.getToken(function (token) {
        request({
            method: 'post',
            uri: _this.message_url + "/mass/sendall?access_token=" + token,
            json: data
        }, function (error, response, body) {
            if (error)
                throw error;
            callback(body);
        });
    });
};

/**
 * 获取菜单信息
 * @param callback
 */
weChatUtil.getMenu = function (callback) {
    let _this = this;
    _this.getToken(function (token) {
        request({
            method: 'get',
            uri: _this.menu_url + "/get?access_token=" + token,
            json: {}
        }, function (error, response, body) {
            if (error)
                throw error;
            callback(body);
        });
    });
};

/**
 * 创建或修改菜单信息
 * @param menuData
 * @param callback
 */
weChatUtil.updateMenu = function (menuData, callback) {
    let _this = this;
    let url=_this.menu_url+"/create";
    if(menuData.matchrule)
        url = _this.menu_url+"/addconditional";
    _this.getToken(function (token) {
        request({
            method: 'post',
            uri: url + "?access_token=" + token,
            json: menuData
        }, function (error, response, body) {
            if (error)
                throw error;
            callback(body);
        });
    });
};

weChatUtil.materialUpload = function (data, callback) {
    data = data || {type: 'image'};
    let _this = this;
    _this.getToken(function (token) {
        let formData = {
            media: fs.createReadStream(data.file)
        };
        request.post({
            url: _this.material_url + "/add_material?access_token=" + token + "&type=" + (data.type || "image"),
            formData: formData
        }, function (err, httpResponse, body) {
            if (err) {
                console.error('upload failed:', err);
                return;
            }
            console.log('Upload successful!  Server responded with:', body);
            //{"media_id":"JN4uNiPgawZ_XQWewhQ5_sq8PMdKKVY_H8Ntoa9bM_4","url":"https:\/\/mmbiz.qlogo.cn\/mmbiz\/gZPrxC4IV0GmFTicUxHOaUYqJ9cRnG6v0ShRgqMtmvibEsUaRKbnBicc5PiaeCukib1eJibnmGeC4D60aVNX7TeDBJ4A\/0?wx_fmt=jpeg"}
            callback(body);
        });
    });
};

weChatUtil.materialList = function(data,callback){
    data = data || {type: 'image',offset:0, count:20};
    let _this = this;
    _this.getToken(function (token) {
        request.post({
            url: _this.material_url + "/batchget_material?access_token=" + token,
            json:data
        }, function (err, httpResponse, body) {
            if (err) {
                console.error('list failed:', err);
                return;
            }
            console.log(body);
            callback(body);
        });
    });
};

weChatUtil.materialGet = function(media_id,callback){
    let _this = this;
    _this.getToken(function (token) {
        request.post({
            url: _this.material_url + "/get_material?access_token=" + token,
            json:{"media_id":media_id}
        }, function (err, httpResponse, body) {
            if (err) {
                console.error('list failed:', err);
                return;
            }
            console.log(body);
            callback(body);
        });
    });
};

weChatUtil.materialDelete = function(media_id,callback){
    let _this = this;
    _this.getToken(function (token) {
        request.post({
            url: _this.material_url + "/del_material?access_token=" + token,
            json:{"media_id":media_id}
        }, function (err, httpResponse, body) {
            if (err) {
                console.error('list failed:', err);
                return;
            }
            console.log(body);
            callback(body);
        });
    });
};

weChatUtil.updateNews = function (type,data, callback) {
    let _this = this;
    _this.getToken(function (token) {
        request.post({
            url: _this.material_url + "/"+type+"_news?access_token=" + token,
            json:data
        }, function (err, httpResponse, body) {
            if (err) {
                console.error('add news failed:', err);
                return;
            }
            console.log("add news:",body);
            callback(body);
        });
    });
};

weChatUtil.updateGroup = function (type,data,callback) {
    let _this = this;
    _this.getToken(function (token) {
        request.post({
            url: _this.group_url + "/"+type+"?access_token=" + token,
            json:data
        }, function (err, httpResponse, body) {
            if (err) {
                console.error('add group failed:', err);
                return;
            }
            console.log("add group:",body);
            callback(body);
        });
    });
};

module.exports = weChatUtil;